package com.dmgis.qxfw.dataservice.businessservice.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UrlHttpRequest
 * @Description TODO
 * @Author sun
 * @Date 2020/11/26 20:10
 * @Version 1.0
 **/
public class UrlHttpRequest {
    public String GetJsonDataByUrl(String ip) {
        String result = "";
        BufferedReader read = null; //读取访问结果
        try {
            //创建url
            URL realurl = new URL(ip);
            //打开连接
            URLConnection connection = realurl.openConnection();
            //建立连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段，获取到cookies等
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line; //循环读取
            while ((line = read.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //POST方法
    public static String httpPostBody(String urlStr, String params, String ticket) {
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);//post不能使用缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("accept", "*/*");// 设置接收数据的格式
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//设置消息头，解决508错误
            connection.setRequestProperty("Content-type", "application/json"); // 设置发送数据的格式
            if (!StringUtil.IsNullOrEmpty(ticket))
                connection.setRequestProperty("Authorization", ticket);
            OutputStreamWriter paramout = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            paramout.write(params);
            paramout.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }

            paramout.close();
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data.toString();
    }

    public static String httpPost(String urlStr, Map<String, Object> params, String ticket) {
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);//post不能使用缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-type", "application/json");
            if (!StringUtil.IsNullOrEmpty(ticket))
                connection.setRequestProperty("Authorization", ticket);
            OutputStreamWriter paramout = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            String paramsStr = "";   //拼接Post 请求的参数
            for (String param : params.keySet()) {
                Object obj = params.get(param);
                if (obj != null && obj != "") {
                    if (obj.getClass().isArray() && obj.getClass().getComponentType() == String.class) {
                        String[] strs = (String[]) obj;
                        paramsStr += "&" + param + "=" + StringUtils.join(strs, ",");
                    } else if (obj.getClass().getTypeName().contains("ArrayList")) {
                        paramsStr += "&" + param + "=" + obj.toString().substring(1, obj.toString().length() - 1);
                    } else
                        paramsStr += "&" + param + "=" + obj;
                }
            }
            if (!paramsStr.isEmpty()) {
                paramsStr = paramsStr.substring(1);
            }
            paramout.write(paramsStr);
            paramout.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }

            paramout.close();
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data.toString();
    }

    //分解类
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param path    path:保存日志文件路径
     * @param content content：日志内容
     */
    public static void writeFile(String path, String content) {
        File writefile;
        try {
            // 通过这个对象来判断是否向文本文件中追加内容
            // boolean addStr = append;
            writefile = new File(path);
            // 如果文本文件不存在则创建它
            if (!writefile.exists()) {
                writefile.createNewFile();
                writefile = new File(path); // 重新实例化
            }
            FileOutputStream fw = new FileOutputStream(writefile, true);
            Writer out = new OutputStreamWriter(fw, "utf-8");
            out.write(content);
            String newline = System.getProperty("line.separator");
            //写入换行
            out.write(newline);
            out.close();
            fw.flush();
            fw.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
